package com.demo2do.boyle.client.web.controller.wechat;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Calendar;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.demo2do.boyle.client.Constant;
import com.demo2do.boyle.client.entity.protocol.wechat.RequestMessage;
import com.demo2do.boyle.client.entity.protocol.wechat.ResponseMessage;
import com.demo2do.boyle.client.handler.CookieHandler;
import com.demo2do.boyle.client.handler.WechatAuthHandler;
import com.demo2do.core.entity.Result;

/**
 * 
 * @author Wilson
 */
@Controller
@RequestMapping
public class WechatListenerController {

    private static final Logger logger = LoggerFactory.getLogger(WechatListenerController.class);

    @Autowired
    private WechatAuthHandler wechatAuthHandler;

    @Autowired
    private CookieHandler cookieHandler;

    /**
     * used for wechat url validate
     * 
     * @param signature
     * @param timestamp
     * @param nonce
     * @param echostr
     * @return
     */
   @ResponseBody
    @RequestMapping(value = "/wechat-listener", method = RequestMethod.GET)
    public String validate(@RequestParam("signature") String signature,
            @RequestParam("timestamp") String timestamp,
            @RequestParam("nonce") String nonce,
            @RequestParam("echostr") String echostr){

    	
        logger.info("validate():" +
                    "\nsignature: " + signature +
                    "\ntimestamp: " + timestamp +
                    "\nnonce: " + nonce +
                    "\nechostr: " + echostr);
        //return echostr;
        return "hi~ 我是 wechat-listener get 请求";
        
    }
    
    /**
     * response message from wechat
     * 
     * @param request
     * @return
     */
	   @ResponseBody
	   @RequestMapping(value = "/wechat-listener", method = RequestMethod.POST, produces = "application/xml")
	   public ResponseMessage onResponse(HttpEntity<RequestMessage> httpEntity) {

    	String nowTime = String.valueOf(Calendar.getInstance().getTimeInMillis()).substring(0, 10);
    	RequestMessage requestMessage = httpEntity.getBody();
    	ResponseMessage responseMessage = new ResponseMessage();
    	
    	responseMessage.setFrom(requestMessage.getTo());
    	responseMessage.setTo(requestMessage.getFrom());
    	responseMessage.setCreateTime(Long.parseLong(nowTime));
    	responseMessage.setType("text");
    	responseMessage.setContent("^_^ 您好，欢迎关注圈圈族！请在注册登录后及时添加个人信息和社交账号资料，我们将在24小时之内进行审核通过，并自动为您匹配符合条件的任务，玩得开心~");
    	
        logger.info("requestMessage:"+requestMessage + 
        			"\n requestMessage.getTo():"+requestMessage.getTo() +
        			"\n requestMessage.getFrom():"+requestMessage.getFrom() +
        			"\n requestMessage.getType():"+requestMessage.getType() +
        			"\n requestMessage.getContent():"+requestMessage.getContent() +
        			"\n responseMessage:"+responseMessage.toString() +
        			"\n from openid: " + requestMessage.getFrom() +
                    "\n type: " + requestMessage.getType());
		return responseMessage;

    }
    
    /**
     * catch wechat menu click redirect url
     * 
     * @param code
     * @param state
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/wechat-menu")
    public String wechatMenu(
            @RequestParam("code") String code,
            @RequestParam("state") String state,
            HttpServletRequest request,
            HttpServletResponse response) {

        String redirectURL = "/login";

        Result result = wechatAuthHandler.exchangeAuthenticateAccessToken(code);

        if (result.isValid()) {

            String openId = (String) result.get("openid");

            logger.info("Retreving open id[" + openId + "] successfully.");

            // Save open id in cookie
            cookieHandler.addCookie(Constant.COOKIE_OPEN_ID, openId, request, response);

            try {
                redirectURL = URLDecoder.decode(state, "UTF-8");
                //remove '#wechat_redirect'
                redirectURL = StringUtils.substringBefore(redirectURL, "#wechat_redirect");
            } catch (UnsupportedEncodingException e) {
                logger.info("state decode exception", e);
            }

        } else {

            logger.info("exchange openid result fail");

        }

        logger.info("redirectURL: " + redirectURL);

        return "redirect:" + redirectURL;

    }

}
